<?php
    class DatatypesModel
    {
        private $db;
        
        public function __construct() {
            $this->db = db::getInstance();
        }
        
        // Get a single datatype
        public function getDatatype($id) {
            if(!empty($id)) {
                $result = $this->db->select('*', 'datatypes', array('where'=>array('id'=>$id)));
                return mysql_fetch_assoc($result);
            }
        }        
        
        // Delete a datatype and the records where it holds a reference to
        public function deleteDatatype($id) {
            if(!empty($id)) {
                $this->db->delete('datatypes', array('id'=>$id));
                $this->db->delete('datatype_option', array('id_datatype'=>$id));
                $this->db->delete('categories', array('id_datatype'=>$id));                
            }
        }
        
        // Add a datatype to the database and return it's ID
        public function addDatatype($values) {
            $this->db->insert('datatypes', $values);            
            // Get the id:
            $id = $this->db->get('id', 'datatypes', $values);
            return $id;
        }
        
        // Update a datatype in the database
        public function updateDatatype($id, $values) {
            $this->db->update('datatypes', $values, array('id'=>$id));
        }
        
        // Link the options to this datatype
        public function linkOptions($id, $options) {            
            // Delete all option links before making new ones:
            $this->db->delete('datatype_option', array('id_datatype'=>$id));
            foreach($options as $option) {
                $this->db->insert('datatype_option', array('id_datatype'=>$id, 'id_option'=>$option['id'], 'hasmany'=>$option['hasmany']));
            }
        }
        
        // Get a list of all the records
        public function getRecords() {
            $records = array();
            $result = $this->db->select('*', 'datatypes', array('orderby'=>'name'));
			while($record = mysql_fetch_assoc($result)) {
                array_push($records, $record);
            }
            return $records;
        }
        
        // Get a list of all the options of this datatype
        public function getOptions($id) {
            $options = array();
            $result = $this->db->select('id_option,hasmany', 'datatype_option', array('where'=>array('id_datatype'=>$id)));
            while($option = mysql_fetch_assoc($result)) {
                $option['hasmany'] = $option['hasmany']==1 ? true : false;
                array_push($options, $option);                            }
            return $options;
        }
    }
?>